<!-- 管理员 -->
<template>
  <div class="Largestbox">
    <!-- 管理员查找和添加 -->
    <div class="Mauser">
      <el-space wrap>
        <el-input v-model="username" @keyup.enter="ManageLists" placeholder="请输入管理员名称" @clear="ManageLists" clearable
          style="width:300px;" />
        <el-button type="primary" :icon="Search" @click="ManageLists">查找</el-button>
        <el-button type="primary" :icon="Edit" @click="AutoCAD">添加</el-button>
      </el-space>
    </div>

    <!-- 管理员表格 -->
    <div class="liao">
      <el-table :data="getManageLists.Lists" style="width: 100%" border>
        <el-table-column prop="id" label="管理员ID" align="center" />
        <el-table-column prop="username" label="管理员名称" align="center" />
        <el-table-column prop="realname" label="真实姓名" align="center" />
        <el-table-column prop="phone" label="电话" align="center" />
        <el-table-column prop="address" label="管理员角色" align="center">
          <template #default="{ row }">
            <el-space wrap>
              <el-tag v-for="item in getRoleNames(row.roleIds)" :key="item.value">{{ item.label }}</el-tag>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" align="center">
          <template #default="scope">
            <div v-show="scope.row.id!=1">
              <el-button type="primary" @click="modify(scope.row)">修改</el-button>
              <el-button type="danger" @click="remove(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页数据 -->
    <PagingList @Change="giterList" :listdata="listdata"></PagingList>


    <!-- 添加和修改弹出框 -->
    <!-- v-if="title=='修改'?false:true" -->
    <el-dialog v-model="dialogFormVisible" :title="title" destroy-on-close>
      <el-form :rules="rules" ref="ruleFormRef" :model="form" label-width="120px" class="demo-ruleForm" :size="formSize"
        status-icon>
        <el-form-item label="角色名称" label-width="120px" required prop="username">
          <el-input v-model="form.username" autocomplete="off" :disabled="title=='修改'?true:false" />
        </el-form-item>
        <el-form-item label="密码" label-width="120px" required prop="password" v-if="title=='添加'?true:false">
          <el-input v-model="form.password" autocomplete="off" type="password" show-password />
        </el-form-item>
        <el-form-item label="手机号" label-width="120px" required prop="phone">
          <el-input v-model="form.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="真实姓名" label-width="120px" required prop="realname">
          <el-input v-model="form.realname" />
        </el-form-item>
        <el-form-item label="角色" label-width="120px" prop="roleIds">
          <el-select v-model="form.roleIds" placeholder="请选择角色" multiple>
            <el-option v-for="(item,index) in  EnumerList.formdata" :key="index" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定
          </el-button>
          <el-button type="primary" @click="resetForm(ruleFormRef)">重置</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { post } from "@/utils/request";
import { Edit, Search } from "@element-plus/icons-vue";
import { Pagination } from "#/index";
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { throttle } from "@/utils/antishake";

const username = ref("");//搜索框数据
const getManageLists = reactive({
  //表格数据
  Lists: [] as string[],
});
const EnumerList = reactive({ //角色枚举数据
  formdata: [] as string[]
})

let listdata = reactive(new Pagination()) //分页数据
// 分页
const giterList = (e: { page: number; limit: number; total: number; flog: { valueOf: () => boolean; }; targetAdminId?: undefined; }) => { //获取下一页的数据并赋值
  listdata = e
  ManageLists()
}
const dialogFormVisible = ref(false) //控制弹出框的显示和隐藏
let title = ref('')//用于判断是创建还是修改




// 初始化管理员数据
const ManageLists = () => {
  let data = {
    _gp: "admin",
    _mt: "list",
    username: username.value,
    page: listdata.page,
    limit: listdata.limit,
  };
  post(data).then((res) => {
    console.log(res);
    let { data } = res;
    getManageLists.Lists.length = 0;
    getManageLists.Lists.push(...data.items);
    listdata.total = data.count
  });
};
ManageLists();

// 初始化角色枚举数据
const EnumerationData = () => {
  let data = {
    _gp: "admin.role",
    _mt: "options"
  }
  post(data).then(res => {
    console.log(res);
    let { errno, errmsg } = res
    EnumerList.formdata.length = 0
    EnumerList.formdata.push(...res.data)
  })
}
EnumerationData()

// 遍历数组
const getRoleNames = (ids: object) => {
  //过滤角色名
  if (ids instanceof Array) { //判断是否为数组
    return EnumerList.formdata.filter(role => ids.some(id => id === role.value))
  }
}


// 添加数据
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
let form = reactive({
  id: '',
  username: '',
  password: '',
  phone: '',
  realname: '',
  roleIds: []
})
const AutoCAD = () => { //打开添加框
  title.value = '添加'
  form.username = '',
    form.password = '',
    form.phone = '',
    form.realname = '',
    form.roleIds = [],
    dialogFormVisible.value = true
}



const inserForm = throttle(function () {
  if (title.value == '添加') {
    let data = {
      _gp: 'admin',
      _mt: 'create',
      adminDTO: JSON.stringify(form)
    }
    post(data).then(res => {
      let { errno, errmsg } = res
      if (200 == errno) {
        ManageLists()
        dialogFormVisible.value = false
        ElMessage.success('添加成功')
      }
    })
  } else if (title.value == '修改') {
    let data = {
      _gp: 'admin',
      _mt: 'edit',
      adminDTO: JSON.stringify(form)
    }
    post(data).then(res => {
      let { errno, errmsg } = res
      if (200 == errno) {
        ManageLists()
        dialogFormVisible.value = false
        ElMessage.success("修改成功！")
      }
    })
  }

}, 500)








// 添加数据
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      inserForm()
    } else {
      console.log('error submit!', fields)
    }
  })
}
//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//验证
const rules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, message: "长度大于6 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3|5|7|8|9]\d{9}$/,
      message: "请输入正确的号码格式",
      trigger: "blur",
    },
  ],
  realname: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa5]{0,}$/,
      message: "请输入正确的格式",
      trigger: "blur",
    },

  ],
  roleIds: [
    {
      required: true,
      message: '请输入角色！',
      trigger: 'change',
    },
  ]
})
// 打开修改框
const modify = (row: string) => {
  title.value = "修改"
  dialogFormVisible.value = true
  Object.assign(form, row)
}
// 修改数据




//删除成功
const remove = throttle(function (row: { id: string }) {
  form.id = row.id
  ElMessageBox.confirm(
    '代理将永久删除该文件?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let data = {
        _gp: 'admin',
        _mt: 'delete',
        id: form.id
      }
      post(data).then(res => {
        let { errno, errmsg } = res
        if (200 == errno) {
          ManageLists()
          dialogFormVisible.value = false
          ElMessage({
            type: 'success',
            message: '恭喜你，廖阳逍先生删除成功！',
          })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}, 500)

</script>

<style lang="less" scoped>
.Largestbox {
  .liao {
    margin: 25px 0px;
  }

  .el-dialog {
    .el-input {
      width: 280px;
      height: 30px;
    }
  }
}
</style>
